<!-- 目标追踪 -->
<template>
  <div class="target_tracking_container">
    <template>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        
        <!-- 总服务部 -->
        <el-tab-pane label="总服务部" name="serviceDepartment">
          <div class="search_box">
            <div class="fr">
              <el-form :model="searchDepartment" :inline="true" class="searchDepartment">
                <el-form-item size="small">
                  <el-select  style="width:230px;" multiple collapse-tags v-model="searchDepartment.schoolIdList" placeholder="选择校区(多选)">
                    <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small">
                  <el-date-picker
                    style="width:195px;"
                    value-format="yyyy"
                    :format="computedYear"
                    v-model="searchDepartment.financialYear"
                    type="year"
                    placeholder="学年">
                  </el-date-picker>
                </el-form-item>

                <div class="btn btn_search " @click="searchDepartmentData">
                  <span  class="btn_txt">查询</span>
                </div>
              </el-form>
              
            </div>
            
            <div class="clear"></div>
          </div>

          <div class="echarts_box" style="overflow:hidden;">
            <h3 class="title">校区年度业绩追踪图</h3>
            <div class="echarts" style="width:100%;height:400px; float: left" id="department"></div>
          </div>

          <div class="table_box" style="width: 76%; margin-left: 8%; margin-bottom: 30px;">
            <h3 class="title" style="margin-bottom: 20px;">年度目标完成情况表</h3>
            <adminTable :tableHead="tableHeadDepartment" :tableData="tableDataDepartment"></adminTable>
          </div>
        </el-tab-pane>
        <!-- 总服务部 end -->

        <!-- 年度 -->
        <el-tab-pane label="年度" name="year">
          <div class="search_box">
            <div class="tab_box fl">
              <div class="btn_tab fl" @click="clickYearTab(2)" :class="{'isActive' : tabId_year == 2}">按人次</div>
              <div class="btn_tab fl" @click="clickYearTab(1)" :class="{'isActive' : tabId_year == 1}">按金额</div>
              <div class="clear"></div>
            </div>
            <div class="fr">
              <el-form :model="searchYear" :inline="true" class="searchYear">
                <el-form-item size="small">
                  <el-select  style="width:230px;" @change="changeSchool_year" v-model="searchYear.schoolId" placeholder="校区">
                    <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small">
                  <el-date-picker
                    style="width:195px;"
                    value-format="yyyy"
                    :format="computedYear"
                    v-model="searchYear.financialYear"
                    type="year"
                    placeholder="学年">
                  </el-date-picker>
                </el-form-item>

                <el-form-item size="small">
                  <el-select  style="width:230px;" clearable v-model="searchYear.productId" placeholder="全部课程产品">
                    <el-option v-for="(item,key) in productList" :key="key" :label="item.productName" :value="item.productId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <div class="btn btn_search " @click="searchYearData">
                  <span  class="btn_txt">查询</span>
                </div>
              </el-form>
              
            </div>
            
            <div class="clear"></div>
          </div>
          
          

          <div class="echarts_box" style="overflow:hidden;">
            <h3 class="title">{{schoolName_year}} {{yearNum}}年度目标追踪图</h3>
            <div class="echarts" style="width:100%;height:400px; float: left" id="year"></div>
          </div>

          <div class="table_box" style="width: 80%; margin-left: 10%;margin-top: 30px;margin-bottom: 30px;">
            <h3 class="title" style="margin-bottom: 15px;">{{schoolName_year}}{{yearNum}} 年度目标完成情况表</h3>
            <adminTable v-show="tabId_year == 2" :tableHead="tableHeadYear_people" :tableData="tableDataYear"></adminTable>
            <adminTable v-show="tabId_year == 1" :tableHead="tableHeadYear_price" :tableData="tableDataYear"></adminTable>
          </div>
        </el-tab-pane>
        <!-- 年度 end-->

    
        <!-- 月度 -->
        <el-tab-pane label="月度" name="month">
          <div class="search_box">
            <div class="tab_box fl">
              <div class="btn_tab fl" @click="clickMonthTab(2)" :class="{'isActive' : tabId_month == 2}">按人次</div>
              <div class="btn_tab fl" @click="clickMonthTab(1)" :class="{'isActive' : tabId_month == 1}">按金额</div>
              <div class="clear"></div>
            </div>
            <div class="fr">
              <el-form :model="searchMonth" :inline="true" class="searchMonth">
                <el-form-item size="small">
                  <el-select  style="width:150px;" @change="changeMonthSchool" v-model="searchMonth.schoolId" placeholder="校区">
                    <el-option v-for="(item,key) in monthPowerSchoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small">
                  <el-date-picker
                    style="width:110px;"
                    value-format="yyyy"
                    format="yyyy年"
                    v-model="searchMonth.financialYear"
                    type="year"
                    placeholder="学年">
                  </el-date-picker>
                </el-form-item>

                

                <el-form-item size="small">
                  <el-date-picker
                    style="width:90px;"
                    value-format="MM"
                    format="M月"
                    v-model="searchMonth.financialMonth"
                    type="month"
                    placeholder="月份">
                  </el-date-picker>
                </el-form-item>

                <el-form-item size="small">
                  <el-select @change="changeProduct" v-model="searchMonth.productId" clearable placeholder="全部课程产品">
                    <el-option v-for="(item,key) in productList" :key="key" :label="item.productName" :value="item.productId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small">
                  <el-select @change="changePerson" clearable  v-model="searchMonth.employeesId" placeholder="员工" style="width:100px;">
                    <el-option v-for="(personItem,key) in personList" :key="key" :label="personItem.employeesName" :value="personItem.employeesId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <div class="btn btn_search" @click="searchMonthData">
                  <span class="btn_txt">查询</span>
                </div>
              </el-form>
              
            </div>
            
            <div class="clear"></div>
          </div>
          
          <h3 class="month_title">{{monthTitle}}</h3>
          <div class="month_info_box">
            <div class="item">
              <div>
                <i class="icon fl"></i>
                <span class="item_title fl">
                  <span v-if="monthShowModel == 'single'">本产品月度目标({{monthUnit}})</span>
                  <span v-else>月度目标业绩({{monthUnit}})</span>
                </span>
                <div class="clear"></div>
              </div>
              <div class="num">{{monthData.cumulativePerformance}}</div>
            </div>
            <div class="item">
              <div>
                <i class="icon fl"></i>
                <span class="item_title fl">
                  <span v-if="monthShowModel == 'single'">本产品本月完成({{monthUnit}})</span>
                  <span v-else>本月完成业绩({{monthUnit}})</span>
                </span>
                <div class="clear"></div>
              </div>
              <div class="num">{{monthData.monthCumulativePerformance}}</div>

            </div>
            <div class="item">
              <div>
                <i class="icon fl"></i>
                <span class="item_title fl">
                  <span v-if="monthShowModel == 'single'">本产品本月完成率</span>
                  <span v-else>本月{{monthUnit2}}业绩完成率</span>
                </span>
                <div class="clear"></div>
              </div>
              <div class="num">{{monthData.monthCumulativeComplete}}</div>

            </div>
            <div class="item">
              <div>
                <i class="icon fl"></i>
                <span class="item_title fl">
                  <span v-if="monthShowModel == 'single'">本产品本月销售冠军</span>
                  <span v-else>本月销售冠军</span>
                </span>
                <div class="clear"></div>
              </div>
              <div class="num">{{monthData.monthSalesChampionName}}</div>

            </div>
          </div>

          <div class="echarts_box flex" style="overflow:hidden;">
            <!-- 左右两图 -->
            <div v-show="monthShowModel == 'double'" style="width: 100%; display:flex;justify-content: space-between;">     
              <div class="item">
                <h3 class="title">{{monthLeftEchartsName}}</h3>
                <div class="monthPeopleBox"  v-show="tabId_month == 2">
                  <div v-show="!showMoreData">
                    <div class="echarts" style="width:100%;height:300px; " id="monthPeopleLeft"></div>
                  </div>
                  <div v-show="showMoreData">
                    <adminTable :tableHead="tableHeadMonthDetail" :tableData="tableDataMonthDetail"></adminTable>
                  </div>
                  
                  <span class="fr more" @click="showMore" v-if="!showMoreData">展开详情<i class="el-icon-caret-bottom"></i></span>
                  <span class="fr reback" @click="reback" v-if="showMoreData">收起<i class="el-icon-caret-right"></i></span>
                  <div class="clear"></div>
                </div>
                <div class="echarts" v-show="tabId_month == 1" style="width:100%;height:300px; float: left" id="monthPriceLeft">2</div>
              </div>
              <div class="item">
                <h3 class="title">{{monthRightEchartsName}}</h3>
                <div class="echarts"  style="width:100%;height:300px; float: left" id="monthPriceRight"></div>
              </div>
            </div>

            <!-- 单产品图 -->
            <div v-show="monthShowModel == 'single'" style="width: 100%">
              <div class="item" style="width: 100%;">
                <h3 class="title">{{monthProductEchartsName}}</h3>
                <div class="echarts" style="width:100%;height:400px;" id="echartsProduct"></div>
              </div>
            </div>
            
          </div>

        </el-tab-pane>
        <!-- 月度 end-->

      </el-tabs>
    </template>

  </div>
</template>


<style>
.monthPeopleBox .admin_table td {
  padding:  2px 0;
}
.monthPeopleBox .admin_table .cell span {
  font-size: 11px !important;
}
/* .echarts > div, .echarts canvas {
  width: 100% !important;
} */
.target_tracking_container .table_box {
  box-shadow: none;
}
.target_tracking_container #pane-month {
  background: #F8F9FA;
}
.target_tracking_container .el-tabs__nav {
  background: #fff;
}
.target_tracking_container .el-tabs__header {
  margin-bottom: 0;
}
.target_tracking_container .el-tabs__content {
  box-shadow: 2px 2px 8px 4px rgba(213,212,212,0.5);
  /* padding-top: 15px; */
  box-sizing: border-box;
  background: #fff;
}
.target_tracking_container .el-tabs--card>.el-tabs__header .el-tabs__nav {
  /* border-bottom: 1px solid #E4E7ED; */
  border-radius: 3px 3px 0 0;
}
.target_tracking_container .el-tabs__item {
  height: 35px;
  line-height: 35px;
  border-bottom: 1px solid #E4E7ED !important;
}
.target_tracking_container .el-tabs__content{
  border-left: 1px solid #E4E7ED;
}

.target_tracking_container .el-tabs__item.is-active {
  color: #FC8434;
  border-bottom: 1px solid #fff !important;
}
</style>
<style scoped>
.month_title {
  color: #FC8434;
  text-align: center;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
}
.more{
  cursor: pointer;
  color: #77A4FF;
  margin-bottom: 20px;
  margin-top: -20px;
  position: relative;
  z-index: 99999;
  padding-right: 15px;
}

.reback{
  cursor: pointer;
  color: #77A4FF;
  padding: 15px;
}

.monthPeopleBox .people_item {
  width: 100%;
}

.echarts_box.flex{
  padding: 0 20px;
  margin-top: 30px;
  padding-bottom: 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
}
.echarts_box.flex .item{
  width: 48%;
  border-radius: 10px;
  background: #fff;
  min-height: 300px;
}
.echarts_box .item .title {
  text-align: left;
  font-size: 14px;
  padding: 15px;
}



.month_info_box{
  display: flex;
  padding: 0 20px;
  box-sizing: border-box;
  justify-content: space-between;
}
.month_info_box .item{
  width: 200px;
  height: 100px;
  border-radius:16px;
  color: #fff;
  padding: 15px;
  box-sizing: border-box;
  /* box-shadow:0px 0px 4px 0px rgba(211,205,205,0.5); */
}



.month_info_box .item .item_title{
  font-size: 14px;
  padding-left: 15px;
}

.month_info_box .num {
  text-align: center;
  margin-top: 15px;
  font-size: 18px;
}


.month_info_box > div:nth-child(1) {
  line-height: 27px;
  background:linear-gradient(293deg,rgba(116,215,254,1) 0%,rgba(148,157,253,1) 100%);
}
.month_info_box > div:nth-child(2) {
  line-height: 27px;
  background:linear-gradient(293deg,rgba(252,132,169,1) 0%,rgba(251,183,138,1) 100%);
}
.month_info_box > div:nth-child(3) {
  line-height: 27px;
  background:linear-gradient(293deg,rgba(90,232,172,1) 0%,rgba(113,217,225,1) 100%);
}
.month_info_box > div:nth-child(4) {
  line-height: 27px;
  background:linear-gradient(117deg,rgba(214,144,230,1) 0%,rgba(254,120,136,1) 100%);
}

.month_info_box .item .icon {
  display: inline-block;
}
.month_info_box > div:nth-child(1) .icon {
  background: url('../../../assets/img/icon2.png') 0 0 no-repeat;
  background-size: 100%;
  width: 25px;
  height: 27px;
}
.month_info_box > div:nth-child(2) .icon {
  background: url('../../../assets/img/icon4.png') 0 0 no-repeat;
  background-size: 100%;
  width: 25px;
  height: 27px;
}
.month_info_box > div:nth-child(3) .icon {
  background: url('../../../assets/img/icon3.png') 0 0 no-repeat;
  background-size: 100%;
  width: 25px;
  height: 27px;
}
.month_info_box > div:nth-child(4) .icon {
  background: url('../../../assets/img/icon1.png') 0 0 no-repeat;
  background-size: 100%;
  width: 25px;
  height: 27px;
}


.table_box{
  /* width: 60%; */
  /* margin: 0 auto; */
  /* margin-left: 15%; */
}
.tab_box .btn_tab.isActive {
  background: #77A4FF;
  color: #fff;
}
.tab_box .btn_tab {
  width:70px;
  height:25px;
  line-height: 25px;
  margin-right: 15px;
  color: #77A4FF;
  font-size: 12px;
  cursor: pointer;
  text-align: center;
  border: 1px solid #77A4FF;
  border-radius:15px;
}
.tab_box .btn_tab:hover {
  background: #77A4FF;
  color: #fff;
}
.tab_box{
  /* margin-left: 30px; */
}
.title {
  color: #485465;
  text-align: center;
  font-size: 18px;
  font-weight: normal;
}
.search_box {
  padding: 15px 15px 0 15px;
  box-sizing: border-box;
}
.btn_search {
  margin-top: 1px;
  padding: 0 20px;
  text-align: center;
  height: 32px;
  font-size: 12px;
  background: #FBA56C;
  line-height: 32px;
}
</style>

<script>
import adminTable from '@/components/assembly/adminTable';
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("targetTracking");


export default {
  name: 'targetTracking',
  data() {
    return {
      activeName: 'serviceDepartment',
      monthShowModel: 'double',
      jwtAuth: {},
      // tabId_year: 2,         // 1金额， 2人次
      // tabId_month: 2,         // 1金额， 2人次

      monthUnit: '人',
      monthUnit2: '人次',
      schoolList: [],
      productList: [],
      personList: [],

      yearNum: '',

      showMoreData: false,

      searchDepartment: {
        schoolIdList: [],
        schoolId: '',
        financialYear: '',
      },
      searchYear: {
        schoolId: '',
        financialYear: '',
        productId: '',
      },
      schoolName_year: '',
      tableHeadDepartment: {   
        data: [
          {
            name: '校区',
            key: 'schoolName',
            align: 'center',
            // width: '70px',
          },
          {
            name: "学年",
            key: "financialYear",
            align: "center",
            // width: '70px',
          },
          {
            name: "年度业绩目标(元)",
            key: "targetAchievement",
            align: "center",
            // width: '70px',
          },
          {
            name: "截至当前年度目标完成率",
            key: "cumulativeComplete",
            align: "center",
            // width: '70px',
          },
          {
            name: "当月完成业绩(元)",
            key: "monthCumulativePerformance",
            align: "center",
            // width: '70px',
          },
        ]
      },
      tableDataDepartment: [],
      
      tableHeadYear_people: {   
        data: [
          {
            name: '全部课程产品名称',
            key: 'productName',
            align: 'center',
          },
          {
            name: `年度目标业绩(人)`,
            key: "productPrice",
            align: "center",
          },
          {
            name: `截至当日已完成(人)`,
            key: "cumulativePerformance",
            align: "center",
          },
          {
            name: "累计完成率",
            key: "cumulativeComplete",
            align: "center",
          },
          {
            name: `本月业绩(人)`,
            key: "monthCumulativePerformance",
            align: "center",
          },
        ]
      },
      tableHeadYear_price: {   
        data: [
          {
            name: '全部课程产品名称',
            key: 'productName',
            align: 'center',
          },
          {
            name: `年度目标业绩(元)`,
            key: "productPrice",
            align: "center",
          },
          {
            name: `截至当日已完成(元)`,
            key: "cumulativePerformance",
            align: "center",
          },
          {
            name: "累计完成率",
            key: "cumulativeComplete",
            align: "center",
          },
          {
            name: `本月业绩(元)`,
            key: "monthCumulativePerformance",
            align: "center",
          },
        ]
      },
      tableDataYear: [],


      //月度
      searchMonth: {
        schoolId: '',
        financialYear: '',
        financialMonth: '',
        productId: '',
        employeesId: '',
        schoolName: '',
      },
      tableHeadMonthDetail: {   
        data: [
          {
            name: '',
            key: 'weekName',
            align: 'center',
          },
          {
            name: '有效单(人)',
            key: 'validlist',
            align: 'center',
            children: [
              {
                name: '目标',
                key: 'validSigning',
                align: 'center',
                width: 48,
                color: '#FFC834'
              },
              {
                name: '完成',
                key: 'completeValidSigning',
                align: 'center',
                width: 48,
                color: '#80D784'
              }
            ]
          },
          {
            name: "试听(人)",
            key: "visit",
            align: "center",
            children: [
              {
                name: '目标',
                key: 'arriveOnVisit',
                align: 'center',
                width: 48,
              },
              {
                name: '完成',
                key: 'completeArriveOnVisit',
                align: 'center',
                width: 48,
              }
            ]
          },
          {
            name: "定金(人)",
            key: "earnestMoney",
            align: "center",
            children: [
              {
                name: '目标',
                key: 'earnestNumber',
                align: 'center',
                width: 48,
              },
              {
                name: '完成',
                key: 'completeEarnestNumber',
                align: 'center',
                width: 48,
              }
            ]
          },
          {
            name: "签单(人)",
            key: "fullMoney",
            align: "center",
            children: [
              {
                name: '目标',
                key: 'targetSigning',
                align: 'center',
                width: 48,
              },
              {
                name: '完成',
                key: 'completeTargetSigning',
                align: 'center',
                width: 48,
              }
            ]
          },
          // {
          //   name: "签单(人)",
          //   key: "monthCumulativePerformance",
          //   align: "center",
          //   children: [
          //     {
          //       name: '目标',
          //       key: 'schoolName',
          //       align: 'center',
          //       width: 40,
          //     },
          //     {
          //       name: '完成',
          //       key: 'schoolName',
          //       align: 'center',
          //       width: 41,
          //     }
          //   ]
          // },
        ]
      },
      tableDataMonthDetail: [],
      monthData: {
        cumulativePerformance: 0,
        monthCumulativePerformance: 0,
        monthCumulativeComplete: 0,
        monthSalesChampionName: '',
        monthSalesChampionPrice: 0,
      },
      monthTitle: '',
      monthPowerSchoolList: [],
      monthLeftEchartsName: '',
      monthRightEchartsName: '',
      monthProductEchartsName: '',

      monthProductName: '',
      monthPersonName: '',
    }
  },
  watch: {
    // tabId(newVal, oldVal) {
    //   console.log(this.tabId)
    // }
  },
  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));
    if(sessionStorage.getItem('trackingTabName')) {
      this.activeName = sessionStorage.getItem('trackingTabName');
    }else{
      this.activeName = 'serviceDepartment';
    }
    this.initSchoolList();
    this.initProductList();


    
  },
  mounted() {

    if(this.vuexDepartmentSearchForm) {
      this.searchDepartment = this.vuexDepartmentSearchForm
    }
    if(this.vuexYearSearchForm) {
      this.searchYear = this.vuexYearSearchForm
    }
    
    
    this.initDepartment(true);
    this.queryMonthSchoolList()
    this.searchYearData(true)
    this.initYear(true);

    if(this.vuexMonthSearchForm) {
      this.searchMonth = this.vuexMonthSearchForm
    }else{
      let date = new Date();
      this.searchMonth.financialYear = date.getFullYear().toString();
      this.searchMonth.financialMonth = (Number(date.getMonth()) + 1).toString();
    }

    if(this.searchMonth.financialMonth.length < 2) {
      this.searchMonth.financialMonth = '0' + this.searchMonth.financialMonth
    }

    // console.log(this.searchMonth.financialMonth.length)
    
    setTimeout(() => {
      this.searchMonthData();
    }, 500);





  },
  // watch: {
  //   mapPowerList: {
  //     handler(newName, oldName) {
  //     },
  //     immediate: true,
  //     deep: true
  //   }
  // },
  
  methods: {
    ...mapMutations([
      "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post"
    ]),

    initSchoolList() {
      this.post({
        API: 'queryAllSchool',
        data: {}
      }).then(res => {
        this.schoolList = res;
        // this.searchYear.schoolId = this.jwtAuth.schoolId || this.schoolList[0].schoolId;
        // this.searchMonth.schoolId = this.jwtAuth.schoolId || this.schoolList[0].schoolId;
        this.changeMonthSchool(this.searchMonth.schoolId)
      }).catch(err => {
        this.$message.error(err);
      })
    },

    queryMonthSchoolList() {
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId
      this.post({
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: this.$route.name,
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        this.monthPowerSchoolList = res;
        if(this.vuexMonthSearchForm == null) {
          this.searchMonth.schoolId = this.monthPowerSchoolList[0].schoolId
        }else{
          this.searchMonth.schoolId = this.vuexMonthSearchForm.schoolId
        }
        this.changeMonthSchool(this.searchMonth.schoolId)
        this.initMonth(true);
      }).catch(err => {
        this.$message.error(err)
      })
    },

    initProductList() {
      this.formGet({
        API: 'queryProductByCourseId',
        data: {
          courseId: '',
        }
      }).then(res => {
        this.productList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    searchDepartmentData() {
      this.updateInfo(["vuexDepartmentSearchForm", this.searchDepartment])
      this.initDepartment(this.searchDepartment)
    },
    initDepartment(bool) {
      let data = this.searchDepartment
      data.schoolId = this.searchDepartment.schoolIdList;
      if(data.schoolId == '') {
        let arr = []
        this.schoolList.forEach(item => {
          arr.push(item.schoolId);
        })
        data.schoolId = arr;
      }

      this.post({
        API: 'targetServicesStatisticalChart',
        data: data
      }).then(res => {
        // console.log(res);
        this.tableDataDepartment = res;
        this.echartsDepartment(res, bool);
      }).catch(err => {
        this.$message.error(err);
      })
    },
    echartsDepartment(data, bool) {
      let myChart = this.$echarts.init(document.getElementById("department"));
      // let data = data;
      let targetData = [];
      let totalData = [];
      let monthData = [];
      let completionData = [];
      let schoolName = [];
      
      if(data) {
        data.forEach(item => {
          let cumulativeComplete = parseFloat(item.cumulativeComplete);
          targetData.push(item.targetAchievement)
          totalData.push(item.cumulativePerformance)
          monthData.push(item.monthCumulativePerformance)
          completionData.push(cumulativeComplete)
          schoolName.push(item.schoolName)
        })
      }

      // console.log(completionData)

      let option = {
        backgroundColor: '#fff',
        grid: {         
          left: '20%',
          top: '10%',
          bottom: 60,
          right: '30%',
        },
        legend: {       // 图例
          data: ['年度目标业绩(元)', '累计完成业绩(元)', '当月完成业绩(元)', '累计完成率(%)'],
          align: 'left',
          icon: 'circle',
          orient: 'vertical',
          right: "5%",
          top: 20,
          bottom: 20,
          textStyle: {
            color: "#485465",
            fontSize: 12,
            fontWeight: 400,
          },
          itemWidth: 14,
          itemHeight: 14,
          itemGap: 35,
        },
        tooltip: {
          trigger: "axis",
          padding: [8, 10],
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: "shadow",
            shadowStyle: {
              color: 'rgba(150,150,150,0.15)',
            },
            textStyle: {
              color: "#fff"
            }
          }
        },
        xAxis: [{
          type: 'category',
          data: schoolName,
          axisLine: {
            show: true
          },
          axisTick: {
            show: false
          },
          axisLabel: {        // x轴 标签
            show: true,
            textStyle: {
              color: "#434e79",
              fontSize: 14,
              fontWeight: 400
            }
          }

        }],
        yAxis: [
          {
            type: 'value',
            name: '金额(元)',
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: { 
              show: true,
              textStyle: {
                color: "#485465",
                fontSize: 12,
                // fontWeight: 400
              }
            }
          },
          {
            type: 'value',
            name: '累计完成率(%)',
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            minInterval: 100,
            axisLabel: {
              formatter: '{value}',
              textStyle: {
                fontSize: 12,
                color: '#485465',
              }
            }
          }
        ],
        series: [
          {
            name: "年度目标业绩(元)",
            type: "bar",
            barMaxWidth: 30,
            z: 0,
            itemStyle: {
              normal: {
                color: "#EDF1FF",
                label: {
                  show: false,
                  textStyle: {
                    fontSize: 12,
                  },
                  position: "top",
                  distance: 10
                }
              }
            },
            data: targetData
          }, 
          {
            name: "累计完成业绩(元)",
            type: "bar",
            silent: true,
            barMaxWidth: 30,
            barGap: '-100%',
            z: 1,
            itemStyle: {
              normal: {
                color: "#8B9DFB",
                label: {
                  show: false,
                  position: 'top',
                  distance: 0,
                  color: '#434e79',
                  fontSize: 12,
                }
              }
            },
            data: totalData
          }, 
          {
            name: "当月完成业绩(元)",
            type: "bar",
            barMaxWidth: 30,
            barGap: '-100%',
            z: 2,
            itemStyle: {
              normal: {
                color: "#FE8697",
              }
            },
            data: monthData
          },
          {
            name:'累计完成率(%)',
            type:'line',
            yAxisIndex: 1,
            lineStyle: {
              width: 4
            },
            itemStyle: {
              normal: {
                color: "#FFC834",
              }
            },
            
            data: completionData
          }
      ]};


      myChart.setOption(option, true);

      window.addEventListener("resize", () => {
        myChart.resize();
      });


      if(bool) {
        myChart.resize();
      }
    },


    searchYearData(bool) {
      this.yearNum = this.searchYear.financialYear
      this.updateInfo(["vuexYearSearchForm", this.searchYear])
      this.initYear(true)
      this.schoolList.forEach(item => {
        if(item.schoolId == this.searchYear.schoolId) {
          this.schoolName_year = item.schoolName;
        }
      })
    },
    initYear(bool) {
      let data = this.searchYear;
      data.type = this.tabId_year;
      // if(data.schoolId) {
        this.post({
          API: 'targetYearStatisticalChart',
          data: data
        }).then(res => {
          this.tableDataYear = res;
          // if(res) {
          this.echartsYear(res, bool);
          // }
        }).catch(err => {
          this.$message.error(err);
        })
      // }
        
    },

    echartsYear(data, bool) {
      let myChart = this.$echarts.init(document.getElementById("year"));
      let targetData = [];
      let totalData = [];
      let monthTargetData = [];
      let completionMonthData = [];
      let completionData = [];

      let chartUnits = [
        ['年度规划分月目标(人)', '当月完成人次(人)',  '月度拆解目标(人)', '当月完成率(%)', '累计完成率(%)',],
        ['年度规划分月目标(元)', '当月完成金额(元)',  '月度拆解目标(元)', '当月完成率(%)', '累计完成率(%)',],
      ]

      let legendArr = [
        ['人次(人)'],
        ['金额(元)']
      ]
      let chartUnit = []
      let legendUnit = []

      if(this.tabId_year == 1) {
        chartUnit = chartUnits[1]
        legendUnit = legendArr[1]
      }else{
        chartUnit = chartUnits[0]
        legendUnit = legendArr[0]
      }

      let date = new Date();
      let currentMonth = (Number(date.getMonth()) + 1);
      if(currentMonth < 9) {
        currentMonth += 12
      };
      let currentMonthIndex = currentMonth - 9


      if(data[0]) {
        data[0].bmTargetYearChildList.forEach((item, index) => {
          targetData.push(item.monthTargetPrice)
          totalData.push(item.monthComplete)
          monthTargetData.push(item.monthTargetComplete)
          if(index <= currentMonthIndex) {
            completionMonthData.push(parseFloat(item.monthCumulativeComplete));
            completionData.push(parseFloat(item.cumulativeComplete));
          }
        })
      }else{
        targetData = [];
        totalData = [];
        monthTargetData = [];
        completionMonthData = [];
        completionData = [];
      }
      
      let option = {
        grid: {         
          left: '10%',
          top: '20%',
          bottom: 60,
          right: '10%',
        },
        legend: {       // 图例
          // data: ['当月目标金额(元)','当月完成金额(元)', '当月完成率(%)', '累计完成率(%)'],
          data: chartUnit,
          icon: 'circle',
          top: '5%',
          textStyle: {
            color: "#485465",
            fontSize: 12,
            fontWeight: 400,
          },
          itemWidth: 14,
          itemHeight: 14,
          itemGap: 35,
        },
        tooltip : {
            trigger: 'axis',
            axisPointer : {            // 坐标轴指示器，坐标轴触发有效
              type : 'shadow',       // 默认为直线，可选为：'line' | 'shadow'   
              shadowStyle: {
                color: 'rgba(150,150,150,0.15)',
              } 
            }
        },
        
        xAxis: [{
          type: 'category',
          data: ['9月', '10月', '11月', '12月','1月', '2月', '3月', '4月','5月', '6月', '7月', '8月'],
          axisLine: {
            show: true
          },
          axisTick: {
            show: false
          },
          axisLabel: {        // x轴 标签
            show: true,
            textStyle: {
              color: "#485465",
              fontSize: 14,
              fontWeight: 400
            }
          }

        }],
        yAxis: [
          {
            type: 'value',
            name: legendUnit,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            minInterval: 1,      // Y轴 整数
            axisLabel: {        // x轴 标签
              show: true,
              textStyle: {
                color: "#485465",
                fontSize: 12,
                // fontWeight: 400
              }
            }
          },
          {
            type: 'value',
            name: '累计完成率(%)',
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            minInterval: 100,
            axisLabel: {
              formatter: '{value}',
              textStyle: {
                fontSize: 12,
                // fontWeight: 400,
                color: '#485465',
              }
            }
          }
        ],
        series : [
          {
            name: chartUnit[0],
            type:'bar',
            barGap: 0,
            itemStyle: {
              normal: {
                color: "#77A4FF",
              }
            },
            data: targetData
          },
          {
            name: chartUnit[1],
            type:'bar',
            barGap: 0,
            itemStyle: {
              normal: {
                color: "#DE8BD4",
              }
            },
            data: totalData
          },
          {
            name: chartUnit[2],
            type:'bar',
            barGap: 0,
            itemStyle: {
              normal: {
                color: "#ACEB8E",
              }
            },
            data: monthTargetData
          },
          {
            name: chartUnit[3],
            type:'line',
            yAxisIndex: 1,
            smooth: 0.4,
            lineStyle: {
              width: 4
            },
            itemStyle: {
              normal: {
                color: "#71D9E1",
              }
            },
            data: completionMonthData
          },
          {
            name: chartUnit[4],
            type:'line',
            yAxisIndex: 1,
            lineStyle: {
              width: 4
            },
            itemStyle: {
              normal: {
                color: "#FFC834",
              }
            },
            data: completionData
          },
        ]
      };

      myChart.setOption(option, true);
      window.addEventListener("resize", () => {
        myChart.resize();
      });

      if(bool) {
        myChart.resize();
      }

    },

    changeSchool_year(e) {
     
    },


    searchMonthData() {
      
      this.changeProduct(this.searchMonth.productId)
      this.changePerson(this.searchMonth.employeesId);

      console.log(this.searchMonth.employeesId);
      console.log(this.monthProductName);

      this.updateInfo(["vuexMonthSearchForm", this.searchMonth])
      console.log(this.searchMonth);
      console.log(this.vuexMonthSearchForm);

      this.showMoreData = false;
      if(this.searchMonth.productId.length > 0) {
        this.monthShowModel = 'single'
        this.initMonthProduct(true);
      }else{
        this.monthShowModel = 'double'
        this.initMonth(true)
      }

      this.getMonthTitle();

      
    },

    

    initMonth(bool) {
      let data = {}
      // let data = this.searchMonth;
      Object.assign(data, this.searchMonth);
      this.getMonthTitle();

      data.productId = []

      if(this.searchMonth.productId) {
        data.productId.push(this.searchMonth.productId)
      }

      data.type = this.tabId_month;

      this.post({
        API: 'monthTrackingChartLeft',
        data: data
      }).then(res => {
        if(res.length > 0) {
          this.monthData = {
            cumulativePerformance: res[0].cumulativePerformance || 0,
            monthCumulativePerformance: res[0].monthCumulativePerformance || 0,
            monthCumulativeComplete: res[0].monthCumulativeComplete || 0,
            monthSalesChampionName: res[0].monthSalesChampionName,
            monthSalesChampionPrice: res[0].monthSalesChampionPrice,
          }
        }else{
          this.monthData = {
            cumulativePerformance: 0,
            monthCumulativePerformance: 0,
            monthCumulativeComplete:0,
            monthSalesChampionName: '',
            monthSalesChampionPrice: 0,
          }
        }
        
        console.log(this.searchMonth.financialMonth)
        this.monthLeftEchartsName    = `${this.searchMonth.schoolName} ${this.searchMonth.financialYear || new Date().getFullYear()}年${this.searchMonth.financialMonth || new Date().getMonth() + 1}月 目标业绩与完成业绩图`
        this.monthRightEchartsName   = `${this.searchMonth.schoolName} ${this.searchMonth.financialYear || new Date().getFullYear()}年${this.searchMonth.financialMonth || new Date().getMonth() + 1}月 产品销售分布图`
        // this.monthProductEchartsName = `${this.searchMonth.schoolName} ${this.searchMonth.financialYear || new Date().getFullYear()}年${this.searchMonth.financialMonth || new Date().getMonth() + 1}月 销售分布图`
        

        this.echartsMonthPriceLeft(res, bool);
        this.echartsMonthPeopleLeft(res, bool);

      }).catch(err => {
        this.$message.error(err);
      })

      this.post({
        API: 'monthTrackingChartRight',
        data: data
      }).then(res => {
        this.echartsMonthPriceRight(res, bool);
      }).catch(err => {
        this.$message.error(err);
      })
      
    },

    getMonthTitle() {
      let schoolName = this.searchMonth.schoolName;
      let year = this.searchMonth.financialYear || new Date().getFullYear();
      let month = this.searchMonth.financialMonth || new Date().getMonth() + 1
      let productName = this.monthProductName || '全部课程产品'
      let personName = this.monthPersonName
      this.monthTitle =  `${schoolName} ${year}年 ${month}月 ${productName} ${personName} 业绩一览`
    },

    initMonthProduct(bool) {
      let data = {}
      data.type = this.tabId_month;
      Object.assign(data, this.searchMonth);

      data.productId = []

      if(this.searchMonth.productId) {
        data.productId.push(this.searchMonth.productId)
      }

      this.post({
        API: 'monthTrackingChartRightDisplay',
        data: data
      }).then(res => {
        this.monthProductEchartsName = `${this.searchMonth.schoolName} ${this.searchMonth.financialYear || new Date().getFullYear()}年${this.searchMonth.financialMonth || new Date().getMonth() + 1}月 销售分布图`
        this.echartsMonthProduct(res, bool);
      }).catch(err => {
        this.$message.error(err);
      })
      
    },

    echartsMonthPriceLeft(data, bool) {
      let myChart = this.$echarts.init(document.getElementById("monthPriceLeft"));
      let week = [];
      let targetData = [];
      let completeData = [];

      if(data.length > 0) {
        data[0].bmTargetMonthChildList.forEach((item, index) => {

          let week1 = item.week.split('~')[0].split(' ')[0].split('-');
          week1 = week1[1] + '.' + week1[2];
          let week2 = item.week.split('~')[1].split(' ')[0].split('-');
          week2 = week2[1] + '.' + week2[2];
          week.push(`第${index+1}期\n${week1}-${week2}`);
          // week.push(`第${index+1}期`);
          targetData.push(item.weekTargetPrice)
          completeData.push(item.weekTargetComplete)
        })
      }

      let option = {
          legend: {       // 图例
            data: ['目标业绩(元)', '完成业绩(元)'],
            icon: 'circle',
            top: '5%',
            textStyle: {
              color: "#485465",
              fontSize: 11,
              fontWeight: 400,
            },
            itemWidth: 10,
            itemHeight: 10,
            itemGap: 35,
          },
          tooltip : {
            trigger: 'axis',
            axisPointer : {            // 坐标轴指示器，坐标轴触发有效
              type : 'shadow',        // 默认为直线，可选为：'line' | 'shadow'
              shadowStyle: {
                color: 'rgba(150,150,150,0.15)',
              } 
            }
          },
          xAxis: {
            type: 'category',
            data: week,
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            axisLabel: {        // x轴 标签
              show: true,
              textStyle: {
                color: "#485465",
                fontSize: 10,
                fontWeight: 400
              }
            }
          },
          yAxis: {
            type: 'value',
            name: '金额(元)',
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            axisLabel: {        // x轴 标签
              show: true,
              textStyle: {
                color: "#485465",
                fontSize: 10,
                fontWeight: 400
              }
            }
          },
          series: [
            {
              name: '目标业绩(元)',
              data: targetData,
              type: 'line',
              smooth: 0.4,
              itemStyle: {
                normal: {
                  color: "#74D7FE",
                }
              },
            },
            {
              name: '完成业绩(元)',
              data: completeData,
              type: 'line',
              smooth: 0.4,
              itemStyle: {
                normal: {
                  color: "#FF98A4",
                }
              },
            },
            /**
            {
              name: '全款(元)',
              data: weekData3,
              type: 'line',
              itemStyle: {
                normal: {
                  color: "#5AE8AC",
                }
              },
            },
            {
              name: '现金流入',
              data: weekData4,
              type: 'line',
              itemStyle: {
                normal: {
                  color: "#8B9DFB",
                }
              },
            }, */
          ]
      };


      myChart.setOption(option, true);
      window.addEventListener("resize", () => {
        myChart.resize();
      });

      if(bool) {
        setTimeout(() => {
          myChart.resize();
        }, 0)
      }
    },

    echartsMonthPriceRight(data, bool) {
      
      let myChart = this.$echarts.init(document.getElementById("monthPriceRight"));
      
      let week = [];
      let productName = []
      let barColor = ['#74D7FE','#949DFD', '#FC84A9', '#FBB78A', '#5AE8AC', '#71D9E1', '#D690E6', '#FE7888']
      let barColor2 = ['#FE7888','#D690E6','#71D9E1','#5AE8AC','#FBB78A','#FC84A9','#949DFD', '#74D7FE',]


      let legendArr = [
        ['人次(人)'],
        ['金额(元)']
      ]
      let legendUnit = []

      if(this.tabId_month == 1) {
        legendUnit = legendArr[1]
      }else{
        legendUnit = legendArr[0]
      }

      let option = {
        grid: {
            // right: '3%',
        },
        legend: {       // 图例
          data: productName,
          icon: 'circle',
          type: 'scroll',
          // orient: 'vertical',
          top: '3%',
          textStyle: {
            color: "#485465",
            fontSize: 12,
            fontWeight: 400,
          },
          itemWidth: 14,
          itemHeight: 14,
          itemGap: 35,
        },
        tooltip : {
          trigger: 'axis',
          show: true,
          axisPointer : {            // 坐标轴指示器，坐标轴触发有效
            type : 'shadow',        // 默认为直线，可选为：'line' | 'shadow'
            shadowStyle: {
              color: 'rgba(150,150,150,0.15)',
            } 
          }
        },
        xAxis: {
          type: 'category',
          data: week,
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          },
          axisLabel: {        // x轴 标签
            show: true,
            textStyle: {
              color: "#485465",
              fontSize: 10,
              fontWeight: 400
            },
          }
        },
        yAxis: {
          type: 'value',
          name: legendUnit,
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          },
          axisLabel: {        // x轴 标签
            show: true,
            textStyle: {
              color: "#485465",
              fontSize: 11,
              fontWeight: 400
            }
          }
        },
        series : [
          
        ]
      };

      
      if(data.length > 0) {
        data.forEach((item, index) => {
          productName.push(item.productName);
          let weekData = [];
          let weekDataTarget = [];
          item.bmTargetMonthChildList.forEach((weekItem, weekIndex) => {
            if(index == 0) {
              let week1 = weekItem.week.split('~')[0].split(' ')[0].split('-');
              week1 = week1[1] + '.' + week1[2];
              let week2 = weekItem.week.split('~')[1].split(' ')[0].split('-');
              week2 = week2[1] + '.' + week2[2];
              week.push(`第${weekIndex+1}期\n${week1}-${week2}`);
              // week.push(`第${weekIndex+1}期`);
            }
            weekData.push(weekItem.weekTargetPrice)
            weekDataTarget.push(weekItem.weekTargetComplete)
          })

          let obj = {
            name: item.productName,
            type:'bar',
            stack: '产品',
            barWidth : 20,
            data:weekData,
            itemStyle: {
              color: barColor[index]
            }
          }
          let targetObj = {
            name: `(目标)${item.productName}`,
            type:'bar',
            stack: '产品目标',
            barWidth : 20,
            barGap: 0,
            data:weekDataTarget,
            itemStyle: {
              color: barColor2[index]
            }
          }
          option.series.push(obj);
          option.series.push(targetObj);
        })

      }else{
        option = {
          legend: {       // 图例
            data: [' ', ' '],
          },
          tooltip : {
            trigger: 'axis',
            show: false,
          },
          xAxis: {
            type: 'category',
            data: [' ', ' '],
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            axisLabel: {        // x轴 标签
              show: true,
              textStyle: {
                color: "#485465",
                fontSize: 12,
                fontWeight: 400
              }
            }
          },
          yAxis: {
            type: 'value',
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            
          },
          series : [
            {
              name: '',
              type:'bar',
              stack: '产品',
              barWidth : 0.00001,
              data:[0, 0, 0, 0, 0],
            },
            {
              name: '',
              type:'bar',
              stack: '产品目标',
              barWidth : 0.00001,
              data:[0, 0, 0, 0, 0],
            }
          ]
        };


        
      }
      
      myChart.setOption(option, true);
      
      window.addEventListener("resize", () => {
        myChart.resize();
      });


      if(bool) {
        setTimeout(() => {
          myChart.resize();
        }, 0)
      }
      /** 
        console.log('1111')
        let dom = document.getElementById("monthPriceRight");
        let myChart = this.$echarts.init(dom);
        
        let app = {};
        // var option = null;
        let hours = ['12a', '1a', '2a', '3a', '4a', '5a', '6a',
                '7a', '8a', '9a','10a','11a',
                '12p', '1p', '2p', '3p', '4p', '5p',
                '6p', '7p', '8p', '9p', '10p', '11p'];
        var days = ['Saturday', 'Friday', 'Thursday',
                'Wednesday', 'Tuesday', 'Monday', 'Sunday'];
        
        var data = [[0,0,5],[0,1,1],[0,2,0],[0,3,0],[0,4,0],[0,5,0],[0,6,0],[0,7,0],[0,8,0],[0,9,0],[0,10,0],[0,11,2],[0,12,4],[0,13,1],[0,14,1],[0,15,3],[0,16,4],[0,17,6],[0,18,4],[0,19,4],[0,20,3],[0,21,3],[0,22,2],[0,23,5],[1,0,7],[1,1,0],[1,2,0],[1,3,0],[1,4,0],[1,5,0],[1,6,0],[1,7,0],[1,8,0],[1,9,0],[1,10,5],[1,11,2],[1,12,2],[1,13,6],[1,14,9],[1,15,11],[1,16,6],[1,17,7],[1,18,8],[1,19,12],[1,20,5],[1,21,5],[1,22,7],[1,23,2],[2,0,1],[2,1,1],[2,2,0],[2,3,0],[2,4,0],[2,5,0],[2,6,0],[2,7,0],[2,8,0],[2,9,0],[2,10,3],[2,11,2],[2,12,1],[2,13,9],[2,14,8],[2,15,10],[2,16,6],[2,17,5],[2,18,5],[2,19,5],[2,20,7],[2,21,4],[2,22,2],[2,23,4],[3,0,7],[3,1,3],[3,2,0],[3,3,0],[3,4,0],[3,5,0],[3,6,0],[3,7,0],[3,8,1],[3,9,0],[3,10,5],[3,11,4],[3,12,7],[3,13,14],[3,14,13],[3,15,12],[3,16,9],[3,17,5],[3,18,5],[3,19,10],[3,20,6],[3,21,4],[3,22,4],[3,23,1],[4,0,1],[4,1,3],[4,2,0],[4,3,0],[4,4,0],[4,5,1],[4,6,0],[4,7,0],[4,8,0],[4,9,2],[4,10,4],[4,11,4],[4,12,2],[4,13,4],[4,14,4],[4,15,14],[4,16,12],[4,17,1],[4,18,8],[4,19,5],[4,20,3],[4,21,7],[4,22,3],[4,23,0],[5,0,2],[5,1,1],[5,2,0],[5,3,3],[5,4,0],[5,5,0],[5,6,0],[5,7,0],[5,8,2],[5,9,0],[5,10,4],[5,11,1],[5,12,5],[5,13,10],[5,14,5],[5,15,7],[5,16,11],[5,17,6],[5,18,0],[5,19,5],[5,20,3],[5,21,4],[5,22,2],[5,23,0],[6,0,1],[6,1,0],[6,2,0],[6,3,0],[6,4,0],[6,5,0],[6,6,0],[6,7,0],[6,8,0],[6,9,0],[6,10,1],[6,11,0],[6,12,2],[6,13,1],[6,14,3],[6,15,4],[6,16,0],[6,17,0],[6,18,0],[6,19,0],[6,20,1],[6,21,2],[6,22,2],[6,23,6]];
        
        let option = {
            tooltip: {},
            visualMap: {
                max: 20,
                inRange: {
                    color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
                }
            },
            xAxis3D: {
                type: 'category',
                data: hours
            },
            yAxis3D: {
                type: 'category',
                data: days
            },
            zAxis3D: {
                type: 'value'
            },
            grid3D: {
                boxWidth: 200,
                boxDepth: 80,
                viewControl: {
                    // projection: 'orthographic'
                },
                light: {
                    main: {
                        intensity: 1.2,
                        shadow: true
                    },
                    ambient: {
                        intensity: 0.3
                    }
                }
            },
            series: [{
                type: 'bar3D',
                data: data.map(function (item) {
                    return {
                        value: [item[1], item[0], item[2]],
                    }
                }),
                shading: 'lambert',

                label: {
                    textStyle: {
                        fontSize: 16,
                        borderWidth: 1
                    }
                },

                emphasis: {
                    label: {
                        textStyle: {
                            fontSize: 20,
                            color: '#900'
                        }
                    },
                    itemStyle: {
                        color: '#900'
                    }
                }
            }]
        };
        if (option && typeof option === "object") {
          console.log('222')
          myChart.setOption(option, true);
          // console.log(myChart.setOption())
          console.log('333')
        }
      
      */
    },

    // 漏斗图
    echartsMonthPeopleLeft(data, bool) {
      let myChart = this.$echarts.init(document.getElementById("monthPeopleLeft"));
      let targetData = [];
      let completeData = [];

      if(data.length > 0) {
        data.forEach(item => {
          targetData.push(item.validSigning);
          targetData.push(item.arriveOnVisit);
          targetData.push(item.earnestNumber);
          targetData.push(item.targetSigning);

          completeData.push(item.completeValidSigning)
          completeData.push(item.completeArriveOnVisit)
          completeData.push(item.completeEarnestNumber)
          completeData.push(item.completeTargetSigning)
        })
      }else{
        targetData.push(0);
        targetData.push(0);
        targetData.push(0);
        targetData.push(0);

        completeData.push(0)
        completeData.push(0)
        completeData.push(0)
        completeData.push(0)
      }

      let option = {
        tooltip: {
          trigger: 'item',
          formatter: "{b} : {c}"
        },
        title: [
          {
            text: '目标业绩',
            left: "19%",
            bottom: '10%',
            textStyle: {
              fontSize: 14,
              color: '#485465',
              fontWeight: 500,
            }
          },
          {
            text: '完成业绩',
            left: '67%',
            bottom: '10%',
            textStyle: {
              fontSize: 14,
              color: '#485465',
              fontWeight: 500,
            }
          }
        ],
        legend: {
          data: ['有效单(人)','试听(人)','定金(人)','签单(人)'],
          icon: 'circle',
          top: '5%',
          left: '17%',
          textStyle: {
            color: "#485465",
            fontSize: 11,
            fontWeight: 400,
          },
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 20,
        },
        series: [
          {
            name: '目标',
            type: 'funnel',
            left: '3%',
            width: '45%',
            sort: 'none',
            label: {
              normal: {
                position: 'inside',
                formatter: ' {c}'
              },
              emphasis: {
                position:'inside',
                formatter: ' {c}'
              }
            },
            labelLine: {
              normal: {
                show: true
              }
            },
            data: [
              {
                value: targetData[0],
                name: '有效单(人)',
                itemStyle: {
                  normal: {
                    color: "#74D6FE",
                  }
                },
                labelLine:{
                  show:true,
                  color: '#ccc'
                },
                label:{
                  show:true
                }
              },
              {
                value: targetData[1],
                name: '试听(人)',
                itemStyle: {
                  normal: {
                    color: "#92A1FD",
                  }
                },
              },
              {
                value: targetData[2],
                name: '定金(人)',
                itemStyle: {
                  normal: {
                    color: "#FBA56C",
                  }
                },
              },
              {
                value: targetData[3],
                name: '签单(人)',
                itemStyle: {
                  normal: {
                    color: "#5AE8AC",
                  }
                },
              },
            ]
          },
          {
            name: '完成',
            type: 'funnel',
            left: '51%',
            width: '45%',
            sort: 'none',
            label: {
              normal: {
                position: 'inside',
                formatter: '{c}',
                // textStyle: {
                //   color: '#fff'
                // }
              },
              emphasis: {
                position:'inside',
                formatter: '{c}'
              }
            },
            // label: {
            //   normal: {
            //     position: 'left'
            //   }
            // },
            data: [
                {
                  value: completeData[0],
                  name: '有效单(人)',
                  itemStyle: {
                    normal: {
                      color: "#74D6FE",
                    }
                  },
                },
                {
                  value: completeData[1],
                  name: '试听(人)',
                  itemStyle: {
                    normal: {
                      color: "#92A1FD",
                    }
                  },
                },
                {
                  value: completeData[2],
                  name: '定金(人)',
                  itemStyle: {
                    normal: {
                      color: "#FBA56C",
                    }
                  },
                },
                {
                  value: completeData[3],
                  name: '签单(人)',
                  itemStyle: {
                    normal: {
                      color: "#5AE8AC",
                    }
                  },
                },
            ]
          }
        ]
      };

      myChart.setOption(option, true);
      window.addEventListener("resize", () => {
        myChart.resize();
      });

      if(bool) {
        setTimeout(() => {
          myChart.resize();
        }, 0)
      }

    },

    echartsMonthProduct(data, bool) {
      let myChart = this.$echarts.init(document.getElementById("echartsProduct"));
      console.log(data)
      let peopleList = []
      let weekName = []
      let totalData = []

      let option = {
        color: ["#FED976", "#C6E1FB", '#FFD1B3', '#A1DAA4', '#A9C2F4', '#FC84A9' ],
        tooltip : {
          trigger: 'axis',
          axisPointer : {            // 坐标轴指示器，坐标轴触发有效
            type : 'shadow',        // 默认为直线，可选为：'line' | 'shadow'
            shadowStyle: {
              color: 'rgba(150,150,150,0.15)',
            } 
          }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        legend: {
          data: peopleList,
          icon: 'circle',
          right: '8%',
          textStyle: {
            color: "#485465",
            fontSize: 12,
            fontWeight: 400,
          },
          itemWidth: 14,
          itemHeight: 14,
          itemGap: 20,
        },
        xAxis : [
          {
            type : 'category',
            data : weekName,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
          }
        ],
        yAxis: [{
          "type": "value",
          "axisLine": {
              lineStyle: {
                  color: '#90979c'
              }
          },
          "axisTick": {
              "show": false
          },
          "axisLabel": {
              "interval": 0,
          },
        }],
        dataZoom:[{
  　　　　type: 'slider',//图表下方的伸缩条
  　　　　show : true, //是否显示
  　　　　realtime : true, //拖动时，是否实时更新系列的视图
  　　　　start : 0, //伸缩条开始位置（1-100），可以随时更改
  　　　　end : 100, //伸缩条结束位置（1-100），可以随时更改
  　　　}],
          
        series: [
          {
            name: "合计",
            type: "line",
            symbolSize:10,
            symbol:'circle',
            smooth: 0.4,
            lineStyle: {
              width: 1.5
            },
            itemStyle: {
              normal: {
                color: "#fec097",
              }
            },
            data: totalData
          },
        ]
      }
     
   
      this.monthData = {
        cumulativePerformance: data.cumulativePerformance || 0,
        monthCumulativePerformance: data.monthCumulativePerformance || 0,
        monthCumulativeComplete: data.monthCumulativeComplete || 0,
        monthSalesChampionName: data.monthSalesChampionName,
        monthSalesChampionPrice: '',  // 冠军金额
      }

      if(data.trackingChartRightDisplayOutList) {
        data.trackingChartRightDisplayOutList.forEach((item, index) => {
          // console.log(item)
          peopleList.push(item.personName)
          
          
          let peopleData = [];
          let peopleTargetData = []
          item.bmTargetMonthChildList.forEach((childItem, childIndex) => {
            // console.log(childItem)
            peopleData.push(childItem.weekTargetPrice)
            peopleTargetData.push(childItem.weekTargetComplete)
          })

          console.log(item.personName);
          
          let obj = {
            name: item.personName,
            type:'bar',
            // stack: item.personName,
            barGap: 0,
            z: 1,
            // barWidth: 20,
            data: peopleData,
          }
          let targetObj = {
            name: '(目标)' + item.personName,
            type:'bar',
            // stack: item.personName,
            // barGap: '-100%',
            z: 0,
            // barWidth: 20,
            color: '#EDF1FF',
            data: peopleTargetData,
          }
          
          option.series.push(obj);
          option.series.push(targetObj);
        })
        peopleList.push('合计')

        // 每一期
        data.trackingChartRightDisplayOutList[0].bmTargetMonthChildList.forEach((item, index) => {
          let week1 = item.week.split('~')[0].split(' ')[0].split('-');
          week1 = week1[1] + '.' + week1[2];
          let week2 = item.week.split('~')[1].split(' ')[0].split('-');
          week2 = week2[1] + '.' + week2[2];

          weekName.push(`第${index+1}期(${week1}-${week2})`);
          
        })

        
        data.bmTargetMonthChildList.forEach(item => {
          if(this.searchMonth.employeesId == '') {
            totalData.push(item.weekTargetPrice);
          }else{
            totalData = [0, 0]
            peopleList[peopleList.length - 1] = ''
          }

          // console.log(totalData)
        })
      }else{
        peopleList = []
        option = {
          color: ["#FED976", "#C6E1FB", '#FFD1B3', '#A1DAA4', '#A9C2F4', '#FC84A9' ],
          tooltip : {
            trigger: 'axis',
            axisPointer : {            // 坐标轴指示器，坐标轴触发有效
              type : 'shadow',        // 默认为直线，可选为：'line' | 'shadow'
              shadowStyle: {
                color: 'rgba(150,150,150,0.15)',
              } 
            }
          },
          legend: {
            data: peopleList,
            icon: 'circle',
            // top: '5%',
            right: '4%',
            textStyle: {
              color: "#485465",
              fontSize: 12,
              fontWeight: 400,
            },
            itemWidth: 14,
            itemHeight: 14,
            itemGap: 20,
          },
          grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
          },
          xAxis : [
            {
              type : 'category',
              data : weekName,
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
            }
          ],
          yAxis : [
            {
              type : 'value',
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
            },
            {
              type: 'value',
              name: '合计',
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              axisLabel: {
                formatter: '{value}',
                textStyle: {
                  fontSize: 12,
                  color: '#fec097',
                }
              }
            }
          ],
          series : [
            {
              name: '',
              type:'bar',
              data: [0]
            },{
              name: '',
              type:'line',
              data: [0]
            }
          ]
        }; 
      }


      myChart.clear();
      myChart.setOption(option, true);

      window.addEventListener("resize", () => {
        myChart.resize();
      });
      if(bool) {
        setTimeout(() => {
          myChart.resize();
        }, 0)
      }
    },



    clickYearTab(index) {
      this.updateInfo(['tabId_year', index])
      // this.tabId_year = index;
      this.initYear();
    },

    clickMonthTab(index) {
      // this.tabId_month = index;
      this.updateInfo(['tabId_month', index])
      // this.initMonth(true);

      if(index == 2) {
        this.showMoreData = false;
      }

      if(this.searchMonth.productId.length > 0) {
        this.monthShowModel = 'single'
        this.initMonthProduct(true);
      }else{
        this.monthShowModel = 'double'
        this.initMonth(true)
      }


      index == 1 ? this.monthUnit = '元' : this.monthUnit = '人'
      index == 1 ? this.monthUnit2 = '金额' : this.monthUnit2 = '人次'
    },

    handleClick(tab, event) {
      // console.log(tab, event);

      sessionStorage.setItem('trackingTabName', tab.name);

      switch (tab.name) {
        case "serviceDepartment":
          this.initDepartment(true);
          break;
        case "year":
          this.searchYearData(true)
          // this.initYear(true);
          break;
        case "month":
          this.searchMonth.productId = '';
          this.monthShowModel = 'double';
          this.queryMonthSchoolList()
          break;
      
        default:
          break;
      }

      // this.$nextTick(() => {
      //   this.echartsDepartment();
      // })
      // this.$nextTick(() => {
      //   this.echartsYear();
      // })
      
    },

    showMore() {
      this.showMoreData = true;
      let data = {}
      Object.assign(data, this.searchMonth);
      data.productId = []
      if(this.searchMonth.productId) {
        data.productId.push(this.searchMonth.productId)
      }

      data.type = this.tabId_month;

      if(!data.financialMonth) {
        data.financialMonth = new Date().getMonth() + 1
      }

      if(data.financialMonth < 10) {
        data.financialMonth = '0' + data.financialMonth
      }else{
        data.financialMonth = data.financialMonth.toString()
      }
      console.log(data);

      this.post({
        API: 'monthTrackingChartDetailsLeft',
        data: data,
      }).then(res => {
        // let arr = [];
        this.tableDataMonthDetail = [];
        res.forEach((item, index) => {
          let week1 = item.week.split('~')[0].split(' ')[0].split('-');
          week1 = week1[1] + '.' + week1[2];
          let week2 = item.week.split('~')[1].split(' ')[0].split('-');
          week2 = week2[1] + '.' + week2[2];
          let obj = {
            weekName : `第${index+1}期</br>${week1}-${week2}`,
            validlist: {
              // validSigning: `<span style="color: red;>${item.validSigning}</span>`,
              validSigning: item.validSigning,
              completeValidSigning: item.completeValidSigning
            },
            visit: {
              arriveOnVisit: item.arriveOnVisit,
              completeArriveOnVisit: item.completeArriveOnVisit
            },
            earnestMoney: {
              earnestNumber: item.earnestNumber,
              completeEarnestNumber: item.completeEarnestNumber
            },
            fullMoney: {
              targetSigning: item.targetSigning,
              completeTargetSigning: item.completeTargetSigning
            }
          } 
          this.tableDataMonthDetail.push(obj);
        })

        // console.log(this.tableDataMonthDetail)

        this.tableDataMonthDetail.forEach(item => {
          item.earnestMoney.completeEarnestNumber = this.computedColor(item.earnestMoney.earnestNumber, item.earnestMoney.completeEarnestNumber)
          item.fullMoney.completeTargetSigning = this.computedColor(item.fullMoney.targetSigning, item.fullMoney.completeTargetSigning)
          item.validlist.completeValidSigning = this.computedColor(item.validlist.validSigning, item.validlist.completeValidSigning)
          item.visit.completeArriveOnVisit = this.computedColor(item.visit.arriveOnVisit, item.visit.completeArriveOnVisit)
        })

      }).catch(err => {
        this.$message.error(err);
      })
    },

    computedColor(target, complete) {
      /**
       * 如果完成比目标小，显示红色
       * 如果完成比目标大，显示绿色
       */
      target = Number(target)
      complete = Number(complete)

      if(complete < target) {
        complete = `<span style="color:red;">${complete}</span>`
      }else{
        complete = `<span style="color:#5AE8AC;">${complete}</span>`
      }
      
      // console.log(complete)
      return complete
    },

    reback() {
      this.showMoreData = false;
    },
    

    changeMonthSchool(e) {
      this.searchMonth.employeesId = ''
      this.schoolList.forEach(item => {
        if(item.schoolId == e) {
          this.searchMonth.schoolName = item.schoolName;
        }
      })

      if(this.vuexMonthSearchForm !== null) {
        console.log('aaaaaa')
        console.log(this.vuexMonthSearchForm.employeesId)
        this.searchMonth.employeesId = this.vuexMonthSearchForm.employeesId
      }

      this.queryAllPerson(e);
    },
    queryAllPerson(schoolId) {
      this.post({
        API: 'queryPositionListBySchoolId',
        data: {
          positionCode: [2, 5],
          // positionCode: "",
          schoolId: this.jwtAuth.schoolId || schoolId,
        }
      }).then(res => {
        this.personList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },


    changePerson(e) {
      this.personList.forEach(item => {
        if(e == item.employeesId) {
          console.log(item)
          this.monthPersonName = item.employeesName
        }
      })

      if(e == '') {
        this.monthPersonName = ''
      }
    },
    changeProduct(e) {
      this.productList.forEach(item => {
        if(e == item.productId) {
          this.monthProductName = item.productName
        }
      })

      console.log(this.monthProductName);

      if(e == '') {
        this.monthProductName = ''
      }
    },

    
    
  },
  computed: {
    ...mapState([
      "vuexDepartmentSearchForm",
      "vuexYearSearchForm",
      "vuexMonthSearchForm",
      "tabId_year",
      "tabId_month",
    ]),
    // ...mapGetters(["selectedIds"]),
    computedYear(e) {
      let year = '';
      if(this.activeName == 'serviceDepartment') {
        year = Number(this.searchDepartment.financialYear)
      }else if (this.activeName == 'year') {
        year = Number(this.searchYear.financialYear)
      }
      return `${year}年9月 - ${year+1}年8月`
    },
    

  },
  components: {
    adminTable,
  },
}

</script>